const express = require('express');
const app = express();
const { addCollection, addDataToCollection, initObject } = require('./action/add')
const { deleteCollection, delDataToCollection } = require('./action/delete')
const { updateCollection, updateDataToCollection } = require('./action/update')
const { queryAllCollection, queryDataToCollection } = require('./action/query')
const multiparty = require('multiparty')
const fs = require('fs')

// 使用swagger API 文档
const swaggerInstall = require('./swagger')
swaggerInstall(app)

//设置处理post请求参数
const bodyParser = require("body-parser");
// app.use(bodyParser.urlencoded({
//   extended: false
// }));
app.use(bodyParser.json())

// 用于在所有HTTP请求方法的路径上加载中间件函数
app.all('*', (req, res, next) => {
	// res.header('Access-Control-Allow-Origin', '*');
	// res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization');
	// res.header('Access-Control-Allow-Methods', '*');
	// res.header('Content-Type', 'application/json;charset=utf-8');
	// 设置响应头
	res.setHeader("Access-Control-Allow-Origin", "*")
	res.setHeader("Access-Control-Allow-Credentials", "true")
	next();
});

// 测试接口
app.get('/api', (req, res) => {
  res.send('访问成功')
})
// 初始化项目
app.post('/api/initObject', (req, res) => {
  initObject((data) => {
    res.send(data)
  })
})
// 创建表
app.post('/api/createCollection', (req, res) => {
  addCollection(req.body, (data) => {
    res.send(data)
  })
})

// 删除表
app.post('/api/deleteCollection/:tableName', (req, res) => {
  deleteCollection(req.params.tableName, (data) => {
    res.send(data)
  })
})
// 更新表名
app.post('/api/updateCollection', (req, res) => {
  updateCollection(req.body, (data) => {
    res.send(data)
  })
})
// 获取所有表名
app.get('/api/queryAllCollection', (req, res) => {
  queryAllCollection((data) => {
    res.send(data)
  })
})
// 添加数据
app.post('/api/addValue/:tableName', (req, res) => {
  console.log(req.body)
  addDataToCollection(req.params.tableName, req.body, (data) => {
    res.send(data)
  })
})
// 删除数据
app.post('/api/delValue/:tableName', (req, res) => {
  delDataToCollection(req.params.tableName, req.body, (data) => {
    res.send(data)
  })
})
// 更新数据
app.post('/api/updateValue/:tableName', (req, res) => {
  updateDataToCollection(req.params.tableName, req.body, (data) => {
    res.send(data)
  })
})
// 查询数据
app.post('/api/queryValue', (req, res) => {
  queryDataToCollection(req.body, (data) => {
    res.send(data)
  })
})
/* 上传文件 */
app.post('/uploadFile', function (req, res) {
    /* 生成multiparty对象，并配置上传目标路径 */
    let form = new multiparty.Form();
    /* 设置编辑 */
    form.encoding = 'utf-8';
    //设置文件存储路劲
    form.uploadDir = './source';
    //设置文件大小限制
    form.maxFilesSize = 2 * 1024 * 1024;
    // form.maxFields = 1000;   //设置所有文件的大小总和//上传后处理
    form.parse(req, function (err, fields, files) {
        let filesTemp = JSON.stringify(files, null, 2);
        if (err) {
            console.log('parse error:' + err);
        } else {
            let inputFile = files.file[0];
            let uploadedPath = inputFile.path;
            let dstPath = './source/' + inputFile.originalFilename;
            // 重命名为真实文件名
            fs.rename(uploadedPath, dstPath, function (err) {
                if (err) {
                    console.log('rename error:' + err);
                }
            });
        }
        res.writeHead(200, {
            'content-type': 'text/plain;charset=utf-8'
        });
        res.write('received upload:\n\n');
        res.end('上传成功')
        // res.end(util.inspect({
        //     fields: fields,
        //     files: filesTemp
        // }));
    });
});
//访问图片
app.get('/source/*', (req, res) => {
    res.sendFile(`./source/${req.url}`);
});

app.listen(9999, function () {
  console.log("服务器正在监听中9999...");
});